package acme.db;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.simpledb.model.CreateDomainRequest;
import com.amazonaws.services.simpledb.model.ListDomainsRequest;
import com.amazonaws.services.simpledb.model.ListDomainsResult;

public class SimpleDB {
	protected static AmazonSimpleDB sdb = null;
	
    static{
    	try {
			sdb = new AmazonSimpleDBClient(new PropertiesCredentials(
					SimpleDB.class.getResourceAsStream("AwsCredentials.properties")));
		} catch (Exception e) {
			//sdb = new AmazonSimpleDBClient(awsCredentials);
			e.printStackTrace();
		}
    }
    
    private static Set<String> domainSet = null;
    
    protected static boolean initDomain(String domainName){
    	boolean hasDomain = true;
    	if(domainSet == null){
    		domainSet = new HashSet<String>();
    		
    		String nextToken = null;
    		while(true){
	    		ListDomainsRequest ldr = new ListDomainsRequest();
	    		if(nextToken != null) ldr.setNextToken(nextToken);
	    		ListDomainsResult results = sdb.listDomains(ldr);
	    		List<String> names = results.getDomainNames();
	    		domainSet.addAll(names);
	    		nextToken = results.getNextToken();
	    		if(nextToken == null) break;
    		}
    	}
    	if(!domainSet.contains(domainName)){
    		sdb.createDomain(new CreateDomainRequest(domainName));
    		domainSet.add(domainName);
    	}
    	return hasDomain;
    }
}
